package com.szholly.plug.safe.login;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.szholly.utils.spring.SpringBeanFactory;
import com.szholly.utils.util.DateUtil;

import java.util.ArrayList;
import java.util.Date;


/**
 * 定义登录锁定问题
 *
 */
public class LoginLock {
	
	// 登录失败次数
	private static Map<String, List<Date>> logins = new HashMap<String, List<Date>>();
	// 登录锁定时间
	private static Map<String, Date> loginLocks = new HashMap<String, Date>();
	
	/**
	 * 查看当前是否可以登录
	 * @param user
	 * @return
	 */
	public static boolean getCanLogin(String user){
		LoginParameter loginParameter = (LoginParameter) SpringBeanFactory.getBean("loginParameter");
		
		if(loginLocks.containsKey(user)){
			Date lockDate = loginLocks.get(user);
			// 相差的小时
			long lockTime = DateUtil.getDiffDayEx2(lockDate);
			if(lockTime>=loginParameter.getLockHour()){
				loginLocks.remove(user);
				return true;
			}else{
				return false;
			}
		}else{
			return true;
		}
	}
	
	/**
	 * 登录失败，记录登录失败
	 * @param user
	 * @return 返回失败的次数
	 */
	public static int setLogin(String user){
		
		LoginParameter loginParameter = (LoginParameter) SpringBeanFactory.getBean("loginParameter");
		
		List<Date> loginTimes = null;
		
		if(logins.containsKey(user)){
			loginTimes = logins.get(user);
		}else{
			loginTimes = new ArrayList<Date>();
			logins.put(user, loginTimes);
		}
		
		loginTimes.add(new Date());
		
		// 5分钟以内，登录失败，就锁定帐号
		int i = loginTimes.size() - 1;
		int count = 0;
		for(;i>=0;i--){
			Date lockDate = loginTimes.get(i);
			long lockFz = DateUtil.getDiffDayEx3(lockDate);
			// 大于5分钟，去掉锁定时间
			if(lockFz>=loginParameter.getLoginMinute()){
				loginTimes.remove(i);
			}else{
				count ++ ;
			}
		}
		
		// 大于3次锁定
		if(count>=loginParameter.getLoginTimes()){
			loginLocks.put(user, new Date());
		}
		return count;
	}
}